package com.shallwead.bna.dialog;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.shallwead.bna.BnA;
import com.shallwead.bna.object.AdFront;
import com.shallwead.bna.util.Constants;
import com.shallwead.bna.util.Logger;
import com.shallwead.bna.util.image.ImageDownloader;

public class AdFrontDialog extends Dialog implements
		android.view.View.OnClickListener {

	public Context mContext;
	public RelativeLayout adfront_layout, adfront_layout_bottom;
	public ImageView adfront_img;
	public Button adfront_btn_close;

	public AdFront adFront;
	public long delay = 0;

	public AdFrontDialog(Context context, AdFront adFront) {
		super(context, android.R.style.Theme_Translucent_NoTitleBar);
		this.mContext = context;
		this.adFront = adFront;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(Constants.LAYOUT_ADFRONT);
		setLayout();
		init();
	}

	public void setLayout() {
		adfront_layout = (RelativeLayout) findViewById(Constants.ID_ADFRONT_LAYOUT);
		adfront_layout_bottom = (RelativeLayout) findViewById(Constants.ID_ADFRONT_LAYOUT_BOTTOM);
		adfront_img = (ImageView) findViewById(Constants.ID_ADFRONT_IMG);
		adfront_btn_close = (Button) findViewById(Constants.ID_ADFRONT_BTN_CLOSE);

		adfront_layout.setOnClickListener(AdFrontDialog.this);
		adfront_layout_bottom.setOnClickListener(AdFrontDialog.this);
		adfront_img.setOnClickListener(AdFrontDialog.this);
		adfront_btn_close.setOnClickListener(AdFrontDialog.this);
	}

	public void init() {
		Log.e("Error", "Error == " + adFront.getName());
		BnA.imgDownloader.download(adFront.imageUrl, adfront_img);

	}

	@Override
	public void onClick(View v) {

		int id = v.getId();
		if (id == adfront_layout.getId()
				|| id == Constants.ID_ADFRONT_LAYOUT_BOTTOM
				|| id == Constants.ID_ADFRONT_IMG) {
			Logger.e("Touch");
			BnA.goAd(mContext, adFront);
			cancel();
		} else if (id == Constants.ID_ADFRONT_BTN_CLOSE) {
			try {
				delay = Long.parseLong(adFront.getDelay()) * 1000;
			} catch (Exception e) {
			}
			CancelHandler.sendEmptyMessageDelayed(0, delay);
		}

	}

	Handler CancelHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			cancel();
		}
	};

	@Override
	public void onBackPressed() {
	}

}